package zjy.android.radapter.adapter;

import androidx.annotation.NonNull;

import java.lang.reflect.Type;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;
import zjy.android.radapter.livedata.ReturnLiveData;

/**
 * @Create zhang
 * @DATE 2021/7/26 0026
 * @DESC
 */
public final class LiveDataCallAdapter<T> implements CallAdapter<T, ReturnLiveData<T>> {

    private final Type responseType;

    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @NonNull
    @Override
    public Type responseType() {
        return responseType;
    }

    @NonNull
    @Override
    public ReturnLiveData<T> adapt(@NonNull Call<T> call) {
        ReturnLiveData<T> liveData = new ReturnLiveData<>();
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
                liveData.postValue(response.body());
            }

            @Override
            public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
                liveData.postThrowable(t);
            }
        });
        return liveData;
    }
}
